<template>
  <div class="table-schema">
    <el-card>
      <div slot="header" class="card-header">
        <span>数据库表结构管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleBatchSave" :loading="batchSaving">
            <i class="el-icon-upload2"></i> 批量保存所有表
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <div class="form-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="数据库配置：">
            <el-select v-model="searchForm.dbConfigId" placeholder="请选择数据库配置" style="width: 200px" @change="onDbConfigChange">
              <el-option v-for="config in dbConfigList" :key="config.id" :label="config.configName" :value="config.id"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="表名：">
            <el-select 
              v-model="searchForm.tableName" 
              placeholder="请选择或输入表名关键词搜索" 
              style="width: 200px" 
              @change="onTableNameChange" 
              :disabled="!searchForm.dbConfigId"
              filterable
              remote
              :remote-method="handleRemoteSearch"
              :loading="tableLoading"
            >
              <el-option v-for="table in tableList" :key="table" :label="table" :value="table"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleGetSchema" :disabled="!searchForm.dbConfigId || !searchForm.tableName || loading">
              <i class="el-icon-search"></i> 获取表结构
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表结构信息 -->
      <div v-if="tableSchema && tableSchema.tableName" class="schema-info" style="margin-top: 20px;">
        <el-card>
          <div slot="header" class="schema-header">
            <span><strong>{{ tableSchema.tableName }}</strong> <small v-if="tableSchema.tableComment">({{ tableSchema.tableComment }})</small></span>
            <el-button type="success" size="small" @click="handleSaveSchema" :loading="saving">
              <i class="el-icon-check"></i> 保存表结构
            </el-button>
          </div>
          
          <div class="table-container">
            <el-table v-loading="columnLoading" :data="tableColumns" stripe style="width: 100%">
              <el-table-column type="index" width="50" label="序号"></el-table-column>
              <el-table-column prop="columnName" label="字段名" width="150"></el-table-column>
              <el-table-column prop="columnType" label="数据类型" width="120"></el-table-column>
              <el-table-column prop="columnLength" label="长度" width="80"></el-table-column>
              <el-table-column prop="isNullable" label="是否可空" width="100">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.isNullable" type="success">是</el-tag>
                  <el-tag v-else type="danger">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="isPrimaryKey" label="是否主键" width="100">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.isPrimaryKey" type="warning">是</el-tag>
                  <el-tag v-else type="info">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="defaultValue" label="默认值" width="150"></el-table-column>
              <el-table-column prop="columnComment" label="注释"></el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
      
      <!-- 保存状态提示 -->
      <el-alert
        v-if="saveStatus.show"
        :title="saveStatus.title"
        :type="saveStatus.type"
        show-icon
        :closable="true"
        @close="saveStatus.show = false"
        style="margin-top: 20px;">
      </el-alert>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'TableSchema',
  data() {
    return {
      searchForm: {
        dbConfigId: '',
        tableName: ''
      },
      // 存储完整的表列表，用于搜索过滤
      fullTableList: [],
      dbConfigList: [],
      tableList: [],
      tableSchema: null,
      tableColumns: [],
      loading: false,
      columnLoading: false,
      tableLoading: false,
      saving: false,
      batchSaving: false,
      saveStatus: {
        show: false,
        title: '',
        type: 'success' // success, warning, error, info
      }
    };
  },
  mounted() {
    this.getDbConfigList();
  },
  methods: {
    // 获取数据库配置列表
    getDbConfigList() {
      this.$api.databaseConfigApi.getAll().then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        this.dbConfigList = data && data.data || [];
      }).catch(err => {
        console.error('获取数据库配置列表失败:', err);
        this.$message.error('获取数据库配置列表失败');
      });
    },
    
    // 数据库配置变更时获取表列表
    onDbConfigChange() {
      if (this.searchForm.dbConfigId) {
        this.getTableList();
      } else {
        this.tableList = [];
        this.fullTableList = [];
        this.searchForm.tableName = '';
        this.tableSchema = null;
        this.tableColumns = [];
      }
    },
    
    // 表名变更时清空表结构信息
    onTableNameChange() {
      this.tableSchema = null;
      this.tableColumns = [];
    },
    
    // 获取表列表
    getTableList() {
      this.loading = true;
      this.$api.schemaApi.getTables(this.searchForm.dbConfigId).then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        const tableData = data && data.data || [];
        if (Array.isArray(tableData)) {
          this.fullTableList = tableData;
          this.tableList = tableData;
          this.searchForm.tableName = '';
          this.tableSchema = null;
          this.tableColumns = [];
        }
      }).catch(err => {
        console.error('获取表列表失败:', err);
        this.$message.error('获取表列表失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 处理表名远程搜索
    handleRemoteSearch(keyword) {
      if (this.fullTableList.length === 0) {
        // 如果完整表列表为空，先加载表列表
        this.getTableList();
        return;
      }
      
      this.tableLoading = true;
      
      // 模拟网络延迟，提升用户体验
      setTimeout(() => {
        if (keyword && keyword.trim()) {
          // 根据关键词过滤表列表
          this.tableList = this.fullTableList.filter(table => 
            table.toLowerCase().includes(keyword.toLowerCase())
          );
        } else {
          // 如果搜索关键词为空，则显示全部表
          this.tableList = this.fullTableList;
        }
        this.tableLoading = false;
      }, 200);
    },
    
    // 获取表结构信息
    handleGetSchema() {
      this.columnLoading = true;
      this.$api.schemaApi.getTableSchema(this.searchForm.dbConfigId, this.searchForm.tableName).then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        this.tableSchema = data && data.schema || null;
        this.tableColumns = data && data.columns || [];
      }).catch(err => {
        console.error('获取表结构信息失败:', err);
        this.$message.error('获取表结构信息失败');
      }).finally(() => {
        this.columnLoading = false;
      });
    },
    
    // 保存表结构信息
    handleSaveSchema() {
      this.saving = true;
      const saveData = {
        dbConfigId: this.searchForm.dbConfigId,
        tableName: this.searchForm.tableName
      };
      this.$api.schemaApi.saveTable(saveData).then(data => {
        // http.js已经处理了响应格式，不需要额外判断
        this.showSaveStatus('success', '表结构信息保存成功');
      }).catch(err => {
        console.error('保存表结构信息失败:', err);
        this.showSaveStatus('error', '保存表结构信息失败');
      }).finally(() => {
        this.saving = false;
      });
    },
    
    // 批量保存所有表结构信息
    handleBatchSave() {
      if (!this.searchForm.dbConfigId) {
        this.$message.warning('请先选择数据库配置');
        return;
      }
      
      this.$confirm('确定要批量保存所有表的结构信息吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchSaving = true;
        const batchData = {
          dbConfigId: this.searchForm.dbConfigId
        };
        this.$api.schemaApi.batchSaveTables(batchData).then(data => {
          // http.js已经处理了响应格式，这里直接获取数据
          this.showSaveStatus('success', 
            `批量保存完成：成功 ${data.successCount || 0} 张表，失败 ${data.failCount || 0} 张表，共 ${data.totalCount || 0} 张表`
          );
        }).catch(err => {
          console.error('批量保存表结构信息失败:', err);
          this.showSaveStatus('error', '批量保存表结构信息失败');
        }).finally(() => {
          this.batchSaving = false;
        });
      }).catch(() => {
        this.$message.info('已取消批量保存');
      });
    },
    
    // 显示保存状态
    showSaveStatus(type, title) {
      this.saveStatus = {
        show: true,
        title: title,
        type: type
      };
      
      // 5秒后自动隐藏
      setTimeout(() => {
        this.saveStatus.show = false;
      }, 5000);
    },
    
    // 刷新
    handleRefresh() {
      this.getDbConfigList();
      if (this.searchForm.dbConfigId) {
        this.getTableList();
      }
    }
  }
};
</script>

<style scoped>
.table-schema {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-container {
  margin-top: 10px;
}

.search-form {
  padding: 10px 0;
}

.schema-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-container {
  margin-top: 10px;
}

.url-tooltip {
  cursor: pointer;
  color: #409EFF;
}

.url-tooltip:hover {
  text-decoration: underline;
}
</style>